package com.xwd.dao.impl;

import com.xwd.dao.DBUtils;
import com.xwd.dao.MiddleDao;
import com.xwd.domain.Menu;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MiddleDaoImpl extends DBUtils implements MiddleDao {
    private String sql = null;

    @Override
    public int insertRoleMenu(int roleId, String[] menuIds) {
        int k=0;
        try {
            sql="insert into middle values(null,?,?)";
            //批量新增
            pps = getPps(sql);
            for (String menu : menuIds) {
                pps.setInt(1,roleId);
                pps.setString(2,menu);
                pps.addBatch();
            }
            pps.executeBatch();
            k=1;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return k;
    }

    @Override
    public List<Menu> findMenuListByRoleId(int roleId) {
        List<Menu> list = new ArrayList<>();
        try {
            sql=" select * from middle where roleid = ? ";
            List param = new ArrayList();
            param.add(roleId);
            resultSet = query(sql, param);
            while (resultSet.next()){
                Menu menu = new Menu();
                menu.setMenuId(resultSet.getInt("menuid"));
                list.add(menu);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeAll();
        }
        return list;
    }

    @Override
    public int deletebyRoleId(int roleId) {
        int i=0;
        try {
            sql="delete from middle where roleid=?";
            List param = new ArrayList();
            param.add(roleId);
            i = update(sql, param);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return i;
    }
}
